/**
 * @license
 * Copyright 2021 Du Tian Wei
 * SPDX-License-Identifier: Apache-2.0
 */
const dgram = require("dgram");
const os = require('os');
let interfaces = os.networkInterfaces();
// console.log('interfaces', interfaces);

let broadcastTargets = [];
for (let name in interfaces) {
    let ipList = interfaces[name];
    for (let i = 0; i < ipList.length; i++) {
        let ipInfo = ipList[i];
        if (ipInfo.internal) {
            continue;
        }
        if (ipInfo.family === 'IPv4') {
            let address = ipInfo.address;
            let netmask = ipInfo.netmask;
            let add = address.split('.');
            let mask = netmask.split('.');
            let n_add = add.map(a => parseInt(a));
            let n_mask = mask.map(a => parseInt(a));
            let n_bro = [];
            for (let i = 0; i < n_add.length; i++) {
                let t = n_add[i] & n_mask[i];
                n_bro[i] = t | (~n_mask[i]) & 255;
            }
            let bro = n_bro.join('.');
            console.log('broadcast target:', bro);
            broadcastTargets.push(bro);
        }
    }
}
let server = dgram.createSocket("udp4");
server.on("close", () => {
    console.log("socket已关闭....");
});

server.on("listening", () => {
    console.log("socket正在监听...");
    server.setBroadcast(true);
    server.setTTL(128);
})

server.on("message", (msg, rinfo) => {
    console.log(`msg from client ${rinfo.address}:${rinfo.port}`);
})

// server.bind(8060);
let interval = 0;
function stop() {
    clearInterval(interval);
}
let message = '';
function setMessage(m) {
    if (m) {
        message = m;
    } else {
        message = '';
    }
}
function start(port) {
    console.log(port);
    stop();
    interval = setInterval(() => {
        let sendingMsg = "UB_SERVER:" + port + "." + message;
        for (let i = 0; i < broadcastTargets.length; i++) {
            let target = broadcastTargets[i];
            server.send(sendingMsg, 65533, target, (err) => {
                if (err) {
                    console.error(err);
                }
            });
        }
    }, 2000);
}
module.exports = {
    start, stop, setMessage
};